<template>
    <div style="width:400px;">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input type="text" v-model="ruleForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="text" placeholder="请输入密码" v-model="ruleForm.password" />
            </el-form-item>
            <button type="button" @click="doLogin()">登录</button>
        </el-form>
    </div>
</template>

<script>
    import Vue from 'vue';
    import {Form,FormItem,Input} from 'element-ui';
    import {mapActions} from "vuex";
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    export default {
        name: "login",
        data(){
            return {
                ruleForm:{
                    username:"",
                    password:""
                },
                rules: {
                    username: [
                        { required: true,validator: this.checkedUsername, trigger: 'blur' }
                    ],
                    password: [
                        {required: true, validator: this.checkedPassword, trigger: 'blur' },
                        {min:6, max: 8, message:"密码长度为6-8位",trigger: 'blur' }
                    ]
                }
            }
        },
        methods:{
            ...mapActions({
                login:"user/login"
            }),
            doLogin(){
                this.$refs['ruleForm'].validate((valid)=>{
                    if (valid) {
                        this.login({cellphone:this.ruleForm.username,password:this.ruleForm.password,success:(res)=>{
                                // console.log(res);
                                if (res.code===200){
                                    this.$router.go(-1)
                                } else{
                                    alert(res.data);
                                }
                            }});
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            checkedUsername(rule, value, callback){
                // console.log(value);
                if(!value){
                    callback(new Error("请输入用户名"));
                }else{
                    callback();
                }
            },
            checkedPassword(rule, value, callback){
                // console.log(value)
                if(!value){
                    callback(new Error("请输入密码"));
                }else{
                    callback();
                }
            }
        }
    }
</script>

<style scoped>

</style>